package com.paic.mhis.hcpms.assessment.biz.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.paic.mhis.common.base.dto.PaginatedQueryDTO;
import com.paic.mhis.common.base.intergration.dao.CommonDAO;
import com.paic.mhis.common.util.BusinessServiceUtil;
import com.paic.mhis.common.util.Constants;
import com.paic.mhis.hcpms.assessment.biz.service.AssessmentIndicatorService;
import com.paic.mhis.hcpms.assessment.biz.service.PerformanceIndicatorsService;
import com.paic.mhis.hcpms.assessment.common.AssessmentConstants;
import com.paic.mhis.hcpms.assessment.common.AssessmentSqlMapIdConstants;
import com.paic.mhis.hcpms.assessment.dto.IndicatorConfigInfoDTO;
import com.paic.mhis.hcpms.assessment.dto.IndicatorDTO;
import com.paic.mhis.hcpms.warning.util.WarnConstants;
import com.paic.pafa.app.biz.service.BusinessServiceException;

/**
 * 
 * Description: 指标体系相关
 * 
 * @author: EX-LUANDEBIAO001
 * @version:
 */
@Service("performanceIndicatorsService")
public class PerformanceIndicatorsServiceImpl implements
		PerformanceIndicatorsService {
	
	@Autowired
	private AssessmentIndicatorService assessmentIndicatorService;

	private static final Logger LOG = Logger
			.getLogger(PerformanceIndicatorsServiceImpl.class);

	@Autowired
	private CommonDAO commonDAO;

	/**
	 * 
	 * Description: 查询各指标权重
	 * 
	 * @return
	 * 
	 *         Modification History: Date Version Author Description
	 *         ------------
	 *         ------------------------------------------------------ 2015-3-25
	 *         mhis_hcpms EX-HUANGJUN003 创建
	 */
	@Override
	@Transactional(rollbackFor = BusinessServiceException.class)
	public List<Map<String, Object>> findFullMark() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = commonDAO.query(
					AssessmentSqlMapIdConstants.ASSESSMENT_FIND_FUMARK, "");
		} catch (Exception e) {
			LOG.error(e, e);
		}
		return list;
	}

	/**
	 * 
	 * Description: 通过前台传来JSON数据,转换为具体集合对象,通过指标体系编码判断有无使用过,来决定保存或修改数据
	 * 
	 * @param param
	 *            前台JSON格式数据
	 * @return
	 * @throws BusinessServiceException
	 * 
	 *             Modification History: Date Version Author Description
	 *             --------
	 *             ----------------------------------------------------------
	 *             2015-2-27 mhis_hcpms EX-LUANDEBIAO001 创建
	 */
	@Override
	@Transactional(rollbackFor = BusinessServiceException.class)
	public Map<String, Object> saveIndicators(String param)
			throws BusinessServiceException {
		Map<String, Object> resultMap = null;

		try {
			List<IndicatorDTO> list = JSONArray.parseArray(param,
					IndicatorDTO.class);
			resultMap = new HashMap<String, Object>();
			
			commonDAO.updateBatch(
					AssessmentSqlMapIdConstants.ASSESSMENT_UPDATE_IND, list);
			resultMap.put(WarnConstants.STATE_KEY,
					WarnConstants.SUCCESS_STATE_VALUE);
			resultMap.put(WarnConstants.MSG_KEY, WarnConstants.SAVE_SUCCESS);

		} catch (Exception e) {
			LOG.error(e, e);
			BusinessServiceUtil.processException(e);
		}
		return resultMap;
	}

	/**
	 * 
	 * Description: 根据指标体系编码,查询具体指标
	 * 
	 * @param param
	 *            指标体系编码
	 * @return
	 * @throws BusinessServiceException
	 * 
	 *             Modification History: Date Version Author Description
	 *             --------
	 *             ----------------------------------------------------------
	 *             2015-2-27 mhis_hcpms EX-LUANDEBIAO001 创建
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<IndicatorDTO> findIndicators(String param)
			throws BusinessServiceException {
		List<IndicatorDTO> list = null;
		try {

			list = commonDAO.query(
					AssessmentSqlMapIdConstants.ASSESSMENT_FIND_IND, param);

		} catch (Exception e) {
			LOG.error(e, e);
			BusinessServiceUtil.processException(e);
		}
		return list;
	}

	/**
	 * 
	 * Description: 查询一级二级三级指标
	 * 
	 * @return 返回的集合
	 * @throws BusinessServiceException
	 * 
	 *             Modification History: Date Version Author Description
	 *             --------
	 *             ----------------------------------------------------------
	 *             2015-3-11 mhis_hcpms EX-ZENGYUANCHAO001 创建
	 */
	@SuppressWarnings("unchecked")
	@Override
	@Transactional(rollbackFor = BusinessServiceException.class)
	public Map<String, Object> findIndicatorsByLevel()
			throws BusinessServiceException {

		Map<String, Object> resultMap = null;
		try {
			List<IndicatorDTO> levelZeroList = commonDAO.query(
					AssessmentSqlMapIdConstants.ASSESSMENT_FIND_IND_BY_LEVEL,
					AssessmentConstants.INDICATOR_LEVEL0);
			List<IndicatorDTO> levelOneList = commonDAO.query(
					AssessmentSqlMapIdConstants.ASSESSMENT_FIND_IND_BY_LEVEL,
					AssessmentConstants.INDICATOR_LEVEL1);
			List<IndicatorDTO> levelTwoList = commonDAO.query(
					AssessmentSqlMapIdConstants.ASSESSMENT_FIND_IND_BY_LEVEL,
					AssessmentConstants.INDICATOR_LEVEL2);

			List<IndicatorDTO> levelThreeList = commonDAO
					.query(AssessmentSqlMapIdConstants.ASSESSMENT_FIND_IND_BY_LEVEL_THREE,
							null);
			Double par1 = null;
			Double par2 = null;
			Double par3 = null;
			StringBuilder sb = new StringBuilder();
			for (IndicatorDTO item : levelThreeList) {
				List<IndicatorConfigInfoDTO> configList= assessmentIndicatorService.getIndicatorConfig(item.getCode(),item.getRegionCode());
				if(configList.isEmpty()){
					item.setIsEnable(AssessmentConstants.IS_VALID_1);
					item.setValue(new BigDecimal(0));
					item.setBackColor("lightgray");
				}else{
					item.setBackColor("white");
				}
				
				configList = orgLevelSort(configList);
				for(IndicatorConfigInfoDTO icDTO :configList){
					if (null != icDTO.getValue()) {
						par1 = icDTO.getValue().doubleValue();
					}
					if (null != icDTO.getUnitValue()) {
						par2 = icDTO.getUnitValue().doubleValue();
					}
					if (null != icDTO.getEmbroiValue()) {
						par3 = icDTO.getEmbroiValue().doubleValue();
					}
					
					sb = classifyParam(sb, icDTO, icDTO.getEvaluationMethod(),
							par1, par2, par3);
					
				}
				
				item.setStandardDesc(sb.toString());
				sb.setLength(0);
				
			}

			List<IndicatorDTO> allList = new ArrayList<IndicatorDTO>();
			allList.addAll(levelZeroList);
			allList.addAll(levelOneList);
			allList.addAll(levelTwoList);
			allList.addAll(levelThreeList);

			resultMap = new HashMap<String, Object>();

			classify(levelZeroList, levelOneList, resultMap);

			classify(levelOneList, levelTwoList, resultMap);

			classify(levelTwoList, levelThreeList, resultMap);

			resultMap
					.put("dataStructure",
							classifyForList(levelZeroList,
									classifyForList(levelOneList, levelTwoList))
									.get(0));

			resultMap.put("level0", levelZeroList);
			resultMap.put("all", allList);
		} catch (Exception e) {
			LOG.error(e, e);
			BusinessServiceUtil.processException(e);
		}
		return resultMap;
	}
	
	private List<IndicatorConfigInfoDTO> orgLevelSort(List<IndicatorConfigInfoDTO> list) {
		Collections.sort(list, new Comparator<IndicatorConfigInfoDTO>() {
			public int compare(IndicatorConfigInfoDTO o1, IndicatorConfigInfoDTO o2) {
				int i1 = 0, i2 = 0;
				try {
					i1 = Integer.parseInt(o1.getOrgLevel());
					i2 = Integer.parseInt(o2.getOrgLevel());
				} catch (Exception e) {
					LOG.info("数据库OrgLevel字段转换异常,请检查....................",e);
				}
				if (i1 > i2) {
					return 1;
				} else if (i1 == i2) {
					return 0;
				} else {
					return -1;
				}
			}
		});
		return list;
	}

	private StringBuilder classifyParam(StringBuilder sb, IndicatorConfigInfoDTO item,
			String method, Double param1, Double param2, Double param3) {
		appendHospitalLevel(sb, item);
		
		if (StringUtils.equals(method, AssessmentConstants.STANDARD_TYPE1)) {
			sb.append("1、横向对比：");
			if (param1 == null) {
				item.setStandardDesc(item.getStandardDesc().replace("(param1)",
						""));
			} else {
				item.setStandardDesc(item.getStandardDesc().replace(
						"95%(param1)", param1.intValue() + "%"));
			}

			if (param2 == null) {
				item.setStandardDesc(item.getStandardDesc().replace("(param2)",
						""));
			} else {
				item.setStandardDesc(item.getStandardDesc().replace(
						"1(param2)", param2.intValue() + ""));
			}

			if (param3 == null) {
				item.setStandardDesc(item.getStandardDesc().replace("(param3)",
						""));
			} else {
				item.setStandardDesc(item.getStandardDesc().replace(
						"20%(param3)", param3.intValue() + "%"));
			}
		} else if (StringUtils.equals(method,
				AssessmentConstants.STANDARD_TYPE2)) {
			sb.append("1、绝对值1：");
		} else if (StringUtils.equals(method,
				AssessmentConstants.STANDARD_TYPE3)) {
			sb.append("1、绝对值2：");
			if (param1 == null) {
				item.setStandardDesc(item.getStandardDesc().replace("(param1)",
						""));
			} else {
				item.setStandardDesc(item.getStandardDesc().replace(
						"100%(param1)", param1.intValue() + "%"));
			}

			if (param2 == null) {
				item.setStandardDesc(item.getStandardDesc().replace("(param2)",
						""));
			} else {
				item.setStandardDesc(item.getStandardDesc().replace(
						"0(param2)", param2.intValue() + ""));
			}
		}

		sb.append(item.getStandardDesc());

		return appendCompareRange(sb, item);
	}

	private void appendHospitalLevel(StringBuilder sb,
			IndicatorConfigInfoDTO item) {
		if(StringUtils.equals(AssessmentConstants.HOSPITAL_LEVEL1, item.getOrgLevel())){
			sb.append("一级及以下医院评分方法<br>");
		}else if(StringUtils.equals(AssessmentConstants.HOSPITAL_LEVEL2, item.getOrgLevel())){
			sb.append("二级医院评分方法<br>");
		}else if(StringUtils.equals(AssessmentConstants.HOSPITAL_LEVEL3, item.getOrgLevel())){
			sb.append("三级医院评分方法<br>");
		}
	}

	private StringBuilder appendCompareRange(StringBuilder sb, IndicatorConfigInfoDTO item) {
		if (StringUtils.equals(item.getCompareRange(),
				AssessmentConstants.COMPARERANGE_TYPE1)) {
			sb.append("<br>2、对比范围：全部机构");
		} else if (StringUtils.equals(item.getCompareRange(),
				AssessmentConstants.COMPARERANGE_TYPE2)) {
			sb.append("<br>2、对比范围：同级机构");
		} else if (StringUtils.equals(item.getCompareRange(),
				AssessmentConstants.COMPARERANGE_TYPE3)) {
			sb.append("<br>2、对比范围：本机构");
		}

		if (StringUtils.equals(item.getEvaluationMethod(),
				AssessmentConstants.STANDARD_TYPE1)) {
			sb.append("<br>3、对比时间：前" + item.getTimeRange() + "个月");
		}
		
		sb.append("<br><br>");
		return sb;
	}

	/**
	 * 
	 * Description: 分级别归类
	 * 
	 * @param levelZeroList
	 * @param levelOneList
	 * @param resultMap
	 * 
	 *            Modification History: Date Version Author Description
	 *            ----------
	 *            --------------------------------------------------------
	 *            2015-2-28 mhis_hcpms EX-LUANDEBIAO001 创建
	 */
	private void classify(List<IndicatorDTO> levelZeroList,
			List<IndicatorDTO> levelOneList, Map<String, Object> resultMap) {
		for (IndicatorDTO itemLZero : levelZeroList) {
			List<IndicatorDTO> list = new ArrayList<IndicatorDTO>();
			for (IndicatorDTO itemLOne : levelOneList) {
				if (StringUtils.equals(itemLZero.getCode(), itemLOne.getPid())) {
					list.add(itemLOne);
				}
			}
			resultMap.put(itemLZero.getCode(), list);
		}
	}

	private List<IndicatorDTO> classifyForList(
			List<IndicatorDTO> levelZeroList, List<IndicatorDTO> levelOneList) {
		for (IndicatorDTO itemLZero : levelZeroList) {

			List<IndicatorDTO> list = new ArrayList<IndicatorDTO>();
			for (IndicatorDTO itemLOne : levelOneList) {
				if (StringUtils.equals(itemLZero.getCode(), itemLOne.getPid())) {
					list.add(itemLOne);
				}
			}

			itemLZero.setList(list);

		}

		return levelZeroList;
	}

	/**
	 * 
	 * Description:分页查询
	 * 
	 * @param page
	 *            页码
	 * @param pageSize
	 *            多少条
	 * @param param
	 *            map集合
	 * @return
	 * @throws BusinessServiceException
	 * 
	 *             Modification History: Date Version Author Description
	 *             --------
	 *             ----------------------------------------------------------
	 *             2015-3-11 mhis_hcpms EX-ZENGYUANCHAO001 创建
	 */
	@Override
	public Map<String, Object> getRankingInfos(int page, int pageSize,
			Map<String, Object> param) throws BusinessServiceException {
		Map<String, Object> result = null;
		try {
			PaginatedQueryDTO dto = new PaginatedQueryDTO();
			dto.setStart(pageSize * (page - 1));
			dto.setLimit(pageSize);
			dto.setParam(param);
		
			result = commonDAO.queryPage(AssessmentSqlMapIdConstants.ASSESSMENT_RANKING_INFO,dto);
			

			result.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
			result.put(Constants.MSG_KEY, Constants.SELECT_SUCCESS);
		} catch (Exception e) {
			LOG.error(e, e);
			BusinessServiceUtil.processException(e);
		}
		return result;
	}

	/**
	 * 
	 * Description:查询信息但不是分页查询
	 * 
	 * @param param
	 * @return
	 * @throws BusinessServiceException
	 * 
	 *             Modification History: Date Version Author Description
	 *             --------
	 *             ----------------------------------------------------------
	 *             2015-3-11 mhis_hcpms EX-ZENGYUANCHAO001 创建
	 */
	@Override
	public List<Map<String, Object>> hospitalRankingTable(
			Map<String, Object> param) throws BusinessServiceException {
		List<Map<String, Object>> result = null;
		try {
			
			result = commonDAO.query(AssessmentSqlMapIdConstants.ASSESSMENT_RANKING_INFO_NO_PAGE,param);
				
		} catch (Exception e) {
			LOG.error(e, e);
			BusinessServiceUtil.processException(e);
		}
		return result;
	}
}
